// pages/dishes_detail/dishes_detail.js
const getdata = require("../../tool/GetDate.js")
const util = require("../../utils/util.js")
var app = getApp();
var uploadUrl = app.globalData.host_url + "gbt/FileManage/UploadPhoto";
var fileName = "";
var hallID = 0;
var dishesID = 0;
var attributeArray = [];
var message = "";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    state: "",
    number: "",
    name: "",
    download_url: app.globalData.host_url + "gbt/FileManage/download/",
    img: "",
    hallID: 0,
    dishesAttributeList: [],
    attributeArray: [],
    objectAttributeArray: [],
    dishesClassTitleArray: [],
    objectDishesClassArray: [],
    dishesClassIndex: 0,
    dishesClassName: "",
    dishesClassID: 0,
    remark: "",
    isEnable: true,
    attributeNameGroup: "",
    isAllSelected: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options);
    fileName = "";
    attributeArray = [];
    message = "";
    hallID = options.hallID;
    dishesID = 0;
    if (options.id) {
      dishesID = options.id;
    }
    this.setData({
      state: options.state,
      hallID: options.hallID,
    });

    this.getDishesClassInfo(hallID);
    this.getAttributeInfo(hallID);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  getAttributeInfo: function (hallID) {
    let that = this;
    //菜品属性 需提供食堂ID 
    getdata.getdata({
      url: "gbt/BasicInfo/AttributePicker/" + hallID + "/",
      data: app.globalData.myUserData.districtID,
      success: function (res) {
        console.log(res.root);
        if (res.root) {
          let attributeList = res.root.arributeArray;
          if (that.data.state === "modify" || that.data.state === "search") {
            //获取菜品详情信息
            that.getDishesDetail(dishesID, res.root.arributeArray);
          } else if (that.data.state === "add") {
            //checkboxGroup 控件赋值
            for (let attributeIndex = 0; attributeIndex < attributeList.length; attributeIndex++) {
              attributeList[attributeIndex].checked = false;
              attributeList[attributeIndex].dishesAttributeIndex = -1;
              attributeList[attributeIndex].state = "add";
            }
          }

          that.setData({
            attributeArray: res.root.arributeTitleArray,
            objectAttributeArray: attributeList,
          });
        }
      }
    });
  },

  getDishesClassInfo: function (hallID) {
    let that = this;
    getdata.getdata({
      url: "gbt/BasicInfo/DishesClassPicker/" + hallID + "/",
      data: app.globalData.myUserData.districtID,
      success: function (res) {
        console.log(res.root);
        if (res.root) {
          let list = res.root.data;
          let titles = [];
          let array = [];
          for (let dataIndex = 0; dataIndex < list.length; dataIndex++) {
            titles.push(list[dataIndex].name);
            array.push(list[dataIndex]);
          }
          that.setData({
            dishesClassTitleArray: titles,
            objectDishesClassArray: array,
          });
        }
      },
    });
  },

  getDishesDetail: function (dishesID, attributeArray) {
    let that = this;
    getdata.getdata({
      url: "gbt/BasicInfo/DishesDetail/" + app.globalData.myUserData.districtID + "/",
      data: dishesID,
      success: function (res) {
        console.log(res.root);
        if (res.root) {
          let dishesAttributeList = res.root.data.attributeList;
          let attributeList = attributeArray;
          let isAllSelected = true; //默认全选
          if (dishesAttributeList) {
            //列表控件赋值
            for (let dishesAttributeIndex = 0; dishesAttributeIndex < dishesAttributeList.length; dishesAttributeIndex++) {
              dishesAttributeList[dishesAttributeIndex].disabled = true;
              dishesAttributeList[dishesAttributeIndex].btnName = "编辑";
              dishesAttributeList[dishesAttributeIndex].state = "modify";
              //属性赋值处理
              for (let attributeIndex = 0; attributeIndex < attributeList.length; attributeIndex++) {
                if (attributeList[attributeIndex].id === dishesAttributeList[dishesAttributeIndex].attributeID) {
                  dishesAttributeList[dishesAttributeIndex].attributeIndex = attributeIndex;
                }
              }
            }
            //checkboxGroup 控件赋值
            for (let attributeIndex = 0; attributeIndex < attributeList.length; attributeIndex++) {
              attributeList[attributeIndex].checked = false;
              attributeList[attributeIndex].dishesAttributeIndex = -1;
              attributeList[attributeIndex].state = "add";
              for (let dishesAttributeIndex = 0; dishesAttributeIndex < dishesAttributeList.length; dishesAttributeIndex++) {
                if (attributeList[attributeIndex].id === dishesAttributeList[dishesAttributeIndex].attributeID) {
                  attributeList[attributeIndex].checked = true;
                  attributeList[attributeIndex].dishesAttributeIndex = dishesAttributeIndex;
                  attributeList[attributeIndex].state = "modify";
                }
              }
              //默认全选，只要有出现未选择项，全选就不成立
              if (!attributeList[attributeIndex].checked) {
                isAllSelected = false;
              }
            }
          }
          fileName = res.root.data.imgUrl;
          hallID = res.root.data.hallID;
          dishesID = res.root.data.id;
          that.setData({
            hallID: res.root.data.hallID,
            number: res.root.data.number,
            name: res.root.data.name,
            img: res.root.data.imgUrl,
            dishesClassName: res.root.data.dishesClassName,
            dishesClassID: res.root.data.dishesClassID,
            remark: res.root.data.remark,
            dishesAttributeList: dishesAttributeList,
            isEnable: res.root.data.isEnable,
            attributeNameGroup: res.root.data.attributeNameGroup,
            objectAttributeArray: attributeList,
            isAllSelected: isAllSelected,
          });
        } else {
          that.setData({
            hallID: 0,
            number: "",
            name: "",
            img: "meal.png",
            dishesClassName: "",
            dishesClassID: 0,
            remark: "",
            dishesAttributeList: [],
            isEnable: true,
            attributeNameGloup: "",
          });
        }
      }
    });
  },

  verify: function () {
    let isFinish = true;
    // if (!fileName) {
    //   message += "菜品图片未设置\n";
    //   isFinish = false;
    // }
    if (!this.data.dishesClassID) {
      message += "菜品分类不能为空\n";
      isFinish = false;
    }
    if (!this.data.number) {
      message += "菜品编码不能为空\n";
      isFinish = false;
    }
    if (!this.data.name) {
      message += "菜品名称不能为空\n";
      isFinish = false;
    }

    return isFinish;
  },

  optDishes: function (data) {
    let that = this;
    getdata.postdata({
      url: "gbt/BasicInfo/OptDishes",
      data: JSON.stringify(data),
      success: function (res) {
        console.log(res.root);
        if (res.root) {
          wx.showToast({
            title: `${res.root.message}`,
            icon: "none",
            duration: 3000,
            success: function (res) {
              if (that.data.state === "add") {
                setTimeout(function () {
                  wx.redirectTo({
                    url: '/pages/dishes_set/dishes_set',
                  });
                }, 2000);
              }
            },
          })

          // //保存完成刷新下菜品详情信息
          // that.getDishesDetail(dishesID, that.data.objectAttributeArray);
          // that.setData({
          //   state: "modify",
          // });
        }
      }
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  // /**
  //  * 用户点击右上角分享
  //  */
  // onShareAppMessage: function () {

  // },

  updateImg: function () {
    let that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        const tempFilePaths = res.tempFilePaths
        wx.uploadFile({
          url: uploadUrl, //仅为示例，非真实的接口地址
          filePath: tempFilePaths[0],
          name: 'file',
          formData: {},
          success(res) {
            const data = res.data
            //do something
            console.log("上传文件返回值");
            console.log(res.data);
            let fileinfo = JSON.parse(res.data);
            console.log(fileinfo);
            fileName = fileinfo.fileName;
            console.log(fileName);
            that.setData({
              img: fileName,
            });
          },
          fail: function (res) {
            console.log("上传失败");
            console.log(res);
          },
          complete: function (res) {

          }
        })
      }
    })
  },

  bindDishesClassPickerChange: function (e) {
    this.setData({
      dishesClassID: this.data.objectDishesClassArray[e.detail.value].id,
      dishesClassName: this.data.objectDishesClassArray[e.detail.value].name,
      dishesClassIndex: e.detail.value,
    });
  },

  onNumberInput: function (e) {
    this.setData({
      number: e.detail.value,
    });
  },

  onNameInput: function (e) {
    this.setData({
      name: e.detail.value,
    });
  },

  onRemarkInput: function (e) {
    this.setData({
      remark: e.detail.value,
    });
  },

  uploadImg: function (e) {
    this.updateImg();
  },

  onSave: function (e) {
    console.log(e);
    let list = this.data.dishesAttributeList;
    if (e.detail.itemState === "add") {
      list.push(e.detail);
    } else if (e.detail.itemState === "modify") {
      list[e.detail.itemIndex] = e.detail;
    }
    this.setData({
      dishesAttributeList: list,
    });
  },

  checkboxChange: function (e) {
    console.log(e);
  },

  onCheckboxClick: function (e) {
    console.log(e.currentTarget.dataset);
    let objectAttributeArray = this.data.objectAttributeArray;
    let dishesAttributeList = this.data.dishesAttributeList;
    let ckItem = e.currentTarget.dataset;
    console.log(dishesAttributeList[0]);
    if (objectAttributeArray[ckItem.index].checked) {
      objectAttributeArray[ckItem.index].checked = false;
    } else {
      objectAttributeArray[ckItem.index].checked = true;
    }

    if (ckItem.state == "add" && objectAttributeArray[ckItem.index].checked) {
      objectAttributeArray[ckItem.index].dishesAttributeIndex = dishesAttributeList.length;
      let dishesAttributeItem = {};
      dishesAttributeItem.attributeID = ckItem.id;
      dishesAttributeItem.hallID = hallID;
      dishesAttributeItem.districtID = app.globalData.myUserData.districtID;
      dishesAttributeItem.state = "add";
      dishesAttributeItem.type = 0;
      dishesAttributeList.push(dishesAttributeItem);
    } else if (ckItem.state == "add" && !objectAttributeArray[ckItem.index].checked) {
      objectAttributeArray[ckItem.index].dishesAttributeIndex = -1;
      //从JSON中移除从索引开始的一个项，包括索引的项
      dishesAttributeList.splice(ckItem.dishesattributeindex, 1);
    }
    if (ckItem.state == "modify" && !objectAttributeArray[ckItem.index].checked) {
      let dishesAttributeItem = dishesAttributeList[ckItem.dishesattributeindex];
      dishesAttributeItem.state = "del";
      dishesAttributeList[ckItem.dishesattributeindex] = dishesAttributeItem;
    } else if (ckItem.state == "modify" && objectAttributeArray[ckItem.index].checked) {
      let dishesAttributeItem = dishesAttributeList[ckItem.dishesattributeindex];
      dishesAttributeItem.state = "modify";
      dishesAttributeList[ckItem.dishesattributeindex] = dishesAttributeItem;
    }

    this.setData({
      objectAttributeArray: objectAttributeArray,
      dishesAttributeList: dishesAttributeList,
    });
  },

  onAllCheckboxClick: function (e) {
    let objectAttributeArray = this.data.objectAttributeArray;
    let dishesAttributeList = this.data.dishesAttributeList;
    let attributeItem = {};
    let dishesAttributeIndex = 0;
    let state = "";
    let dishesAttributeItem = {};

    //同步用户操作 全选或者取消全选
    if (this.data.isAllSelected) {
      this.setData({
        isAllSelected: false,
      });
    } else if (!this.data.isAllSelected) {
      this.setData({
        isAllSelected: true,
      });
    }

    console.log(objectAttributeArray);
    for (let attributeIndex = 0; attributeIndex < objectAttributeArray.length; attributeIndex++) {
      //待用变量
      attributeItem = objectAttributeArray[attributeIndex];
      dishesAttributeIndex = attributeItem.dishesAttributeIndex;
      state = attributeItem.state;
      if (state === "add" && this.data.isAllSelected && objectAttributeArray[attributeIndex].dishesAttributeIndex == -1) {
        //直接赋值
        objectAttributeArray[attributeIndex].checked = true;
        objectAttributeArray[attributeIndex].dishesAttributeIndex = dishesAttributeList.length;
        dishesAttributeItem = {};
        dishesAttributeItem.attributeID = attributeItem.id;
        dishesAttributeItem.hallID = hallID;
        dishesAttributeItem.districtID = app.globalData.myUserData.districtID;
        dishesAttributeItem.state = "add";
        dishesAttributeItem.type = 0;
        dishesAttributeList.push(dishesAttributeItem);
      } else if (state === "add" && !this.data.isAllSelected) {
        //直接赋值
        objectAttributeArray[attributeIndex].checked = false;
        objectAttributeArray[attributeIndex].dishesAttributeIndex = -1;
        //从JSON中移除从索引开始的一个项，包括索引的项
        dishesAttributeList.splice(dishesAttributeIndex, 1);
      } else if (state === "modify" && this.data.isAllSelected) {
        //直接赋值
        objectAttributeArray[attributeIndex].checked = true;
        dishesAttributeItem = {};
        dishesAttributeItem = dishesAttributeList[dishesAttributeIndex];
        dishesAttributeItem.state = "modify";
        dishesAttributeList[dishesAttributeIndex] = dishesAttributeItem;
      } else if (state === "modify" && !this.data.isAllSelected) {
        //直接赋值
        objectAttributeArray[attributeIndex].checked = false;
        dishesAttributeItem = {};
        dishesAttributeItem = dishesAttributeList[dishesAttributeIndex];
        dishesAttributeItem.state = "del";
        dishesAttributeList[dishesAttributeIndex] = dishesAttributeItem;
      }
    }

    this.setData({
      objectAttributeArray: objectAttributeArray,
      dishesAttributeList: dishesAttributeList,
    });
  },

  onDel: function (e) {
    console.log(e);
    let list = this.data.dishesAttributeList;
    if (e.detail.itemState == "add") {
      list.push(e.detail);
    } else if (e.detail.itemState == "modify") {
      list[e.detail.itemIndex] = e.detail;
    }
    this.setData({
      dishesAttributeList: list,
    });
  },

  switchChange: function (e) {
    this.setData({
      isEnable: e.detail.value,
    });
  },

  onConfirm: function (e) {
    let isFinish = this.verify();
    if (isFinish) {
      if (!fileName) {
        fileName = "meal.png";
      }
      let param = {};
      param.id = dishesID;
      param.state = this.data.state;
      param.number = this.data.number;
      param.name = this.data.name;
      param.imgUrl = fileName;
      param.districtID = app.globalData.myUserData.districtID;
      param.hallID = this.data.hallID;
      param.dishesClassID = this.data.dishesClassID;
      param.remark = this.data.remark;
      param.isEnable = this.data.isEnable;
      param.dishesAttribute = this.data.dishesAttributeList;
      console.log(param);
      this.optDishes(param);
    } else {
      wx.showModal({
        title: '温馨提示',
        content: `${message}`,
        showCancel: false,
      });
      message = "";
    }
  },

  onDelDishes: function (e) {
    let that = this;
    wx.showModal({
      title: '温馨提示',
      content: `是否删除菜品 ${this.data.number}`,
      success: function (e) {
        if (e.confirm) {
          let param = {};
          param.id = dishesID;
          param.state = "del";
          param.number = that.data.number;
          param.name = that.data.name;
          param.imgUrl = fileName;
          param.districtID = app.globalData.myUserData.districtID;
          param.hallID = that.data.hallID;
          param.dishesClassID = that.data.dishesClassID;
          param.remark = that.data.remark;
          param.isEnable = that.data.isEnable;
          param.dishesAttribute = that.data.dishesAttributeList;
          console.log(param);
          that.optDishes(param);
        }
      },
    });
  }
})